package com.alifi.crm.biz.lottery;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alifi.crm.biz.guess.EmployeeGuessManagerImpl;
import com.alifi.crm.biz.util.SimpleDateUtil;
import com.alifi.crm.dal.guess.TransmitLogDAO;
import com.alifi.crm.dal.lottery.AmountDAO;
import com.alifi.crm.dal.lottery.EmployeeDAO;
import com.alifi.crm.dal.lottery.LogDAO;
import com.alifi.crm.dal.lottery.PrizeDAO;
import com.alifi.crm.dal.lottery.WinRecordDAO;
import com.alifi.crm.dal.object.AmountDO;
import com.alifi.crm.dal.object.EmployeeDO;
import com.alifi.crm.dal.object.LogDO;
import com.alifi.crm.dal.object.PrizeDO;
import com.alifi.crm.dal.object.TransmitLogDO;
import com.alifi.crm.dal.object.WinRecordDO;

/**
 * 抽奖活动实现类
 * 
 * @author wb_liangzhou.yan
 * @version $Id: LotteryManagerImpl.java, v 0.1 2013-4-24 下午03:32:43 wb_liangzhou.yan Exp $
 */
public class LotteryManagerImpl implements LotteryManager {
    
    private static final Logger      logger = LoggerFactory.getLogger(EmployeeGuessManagerImpl.class);
    
    private static Random random = new Random();
    
    private static String TYPE ="3";
    
    private static final String PRIZETYPE50 = "50";
    
    private static final String PRIZETYPE100 = "100";
    
    private static final String PRIZETYPE2 = "2";
    
    private static final String PRIZETYPE5 = "5";
    
    private static final String ACTIVITY_NAME = "529";
    
    @Autowired
    private EmployeeDAO employeeDAO;
    
    @Autowired
    private PrizeDAO    prizeDAO;
    
    @Autowired
    private WinRecordDAO    winRecordDAO;
    
    @Autowired
    private TransmitLogDAO transmitLogDAO;
    
    @Autowired
    private TransactionTemplate transactionTemplate;
    
    @Autowired
    private LogDAO logDAO;
    
    @Autowired
    private AmountDAO amountDAO;

    @Override
    public EmployeeDO getEmployeeInfo(String employeeNum) {
        return employeeDAO.getEmployeeInfo(employeeNum);
    }

    @Override
    public List<WinRecordDO> getWinRecords() {
        return winRecordDAO.getWinRecords(TYPE, 30);
    }

    @Override
    public LotteryResult lottery(String employeeNum, String nickName, String realName) {
        EmployeeDO employee = employeeDAO.getEmployeeInfo(employeeNum);
        AmountDO amountDO = amountDAO.getAmount(employeeNum);
        //判断是否老用户
        boolean isOldUser = false;
        if(amountDO != null && amountDO.getIsUsed() == 1){
        	isOldUser = true;
        }
        
        // 非目标用户
        if(employee == null){
            return LotteryResult.不准入;
        }
        
        if(employee.getLotteryTimes() >=2){
            return LotteryResult.用完2次;
        }
        
        if(employee.getAvailLotteryTime() == 0){
        	int transmitTimes = transmitLogDAO.countTransmitTimesByEmployeeNumByModifier(employeeNum, ACTIVITY_NAME);
        	
            return transmitTimes == 0 ? LotteryResult.转发0次 : LotteryResult.转发1次;
        }

        //抽奖具体逻辑
        return lotteryLogic(employeeNum, employee.getLotteryTimes().intValue(), nickName, realName, isOldUser);
    }
    
    private LotteryResult lotteryLogic(String employeeNum, int lotteryTimes,String nickName, String realName, boolean isOldUser) {
        //先抽大奖，概率1/200
        int large = random.nextInt(400);
        if(large == 100){
            if(hasLagreLottery(PRIZETYPE100)){
                //还有奖，获取奖品
                updateLotteryAll(employeeNum, PRIZETYPE100, nickName, realName);
                if(lotteryTimes ==0){
                    return LotteryResult.第一次100;
                }else{
                    return LotteryResult.第二次100;
                }
            }
        }else if(large == 50){
            if(hasLagreLottery(PRIZETYPE50)){
                //还有奖，获取奖品
                updateLotteryAll(employeeNum, PRIZETYPE50, nickName, realName);
                if(lotteryTimes ==0){
                    return LotteryResult.第一次50;
                }else{
                    return LotteryResult.第二次50;
                }
            }
        }
               
        //抽不中大奖再抽小奖，第一次5%, 第二次老用户2%, 新用户5%
        if(lotteryTimes == 0){
            updateLotteryAll(employeeNum, PRIZETYPE5, nickName, realName);
            return LotteryResult.第一次5;//第一次抽奖不出现2的数据
        } else {
            updateLotteryAll(employeeNum, isOldUser ? PRIZETYPE2 : PRIZETYPE5, nickName, realName);
            return isOldUser ? LotteryResult.第二次2 : LotteryResult.第二次5;
        }
    }
    
    //事物控制更新中奖后的信息。
    private void updateLotteryAll(final String employeeNum, final String prizeType, final String nickName, final String realName){
        transactionTemplate.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                //更新抽奖次数和可用次数
                employeeDAO.updateEmployee(employeeNum);
                //更新奖品数量
                //prizeDAO.updatePrizeCount(prizeType);
                //插入中奖纪录
                WinRecordDO winRecord = new WinRecordDO();
                winRecord.setEmployeeNum(employeeNum);
                winRecord.setNickName(nickName);
                winRecord.setPrizeType(prizeType);
                winRecord.setRealName(realName);
                winRecord.setType(TYPE);
                winRecordDAO.insertWinRecord(winRecord);
                return null;
            }
        });
    }
    
    //判断大奖有没有发完
    private boolean hasLagreLottery(String prizeType){
        
        //PrizeDO prize = prizeDAO.getPrizeByType(prizeType);
    	int count = winRecordDAO.getWinCountByPiztype(prizeType, TYPE, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
       
    	int prizecount = 0;
        if("100".equals(prizeType)){
            prizecount = 5;
        }else if("50".equals(prizeType)){
            prizecount = 10;
        }
        
        return prizecount > count;
    }
    
    
    
    
    
    /**
     * 如果当前时间等于0530或者0529,返回true,否则返回false
     * @return
     */
    public static boolean isEqualDate(){
        String currentDateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        return currentDateStr.equals("20130529") || currentDateStr.equals("20130530");
    }
    

    @Override
    public void addTransmitLog(String employeeNum, String recipient) {
        if(StringUtil.isBlank(employeeNum) || StringUtil.isBlank(recipient)){
            logger.error("employeeNum or recipient is null");
            return;
        }
        //自己不能给自己增加次数
        if(StringUtil.equalsIgnoreCase(employeeNum, recipient)){
            if(logger.isInfoEnabled()){
                logger.info("employeeNum is equal to recipient, employeeNum=" + employeeNum);
            }
            return;
        }
        
        EmployeeDO employeeDO = employeeDAO.getEmployeeInfo(employeeNum);
        if(employeeDO == null){
            logger.warn("转发用户不准入, employeeNum=" + employeeNum);
            return;
        }
        
        //同一个人点多次不会增加次数
        TransmitLogDO visitLog = transmitLogDAO.selectByEmployeeNumAndRecipient(employeeNum, recipient);
        if(visitLog != null){
            if(logger.isInfoEnabled()){
                logger.info("this body has already transmited, employeeNum=" + employeeNum + ",recipient="+ recipient);
            }
            // 更新最后一次访问时间
            visitLog.setModifier(ACTIVITY_NAME);
            visitLog.setGmtModified(new Date());
            transmitLogDAO.update(visitLog);
        } else {
            //增加转发
            transmitLogDAO.save(genTransmitLogDO(employeeNum,recipient));
        }

        int transmitTimes = transmitLogDAO.countTransmitTimesByEmployeeNumByModifier(employeeNum, ACTIVITY_NAME);
        //总次数=可用抽奖次数 + 抽奖次数
        int countall = employeeDO.getAvailLotteryTime().intValue() + employeeDO.getLotteryTimes().intValue();
        //更新基本信息表的可用抽奖次数(转发次数>=1 && (可用抽奖次数加上抽奖次数)<2)
        if(transmitTimes >= 2 && countall < 2){
            //增加一次可用抽奖次数
            employeeDAO.updateAvailTime(employeeNum);
        }
    }
    
    
    private TransmitLogDO genTransmitLogDO(String employeeNum,String recipient){
        TransmitLogDO transmitLogDO = new TransmitLogDO();
        transmitLogDO.setEmployeeNum(employeeNum);
        transmitLogDO.setRecipient(recipient);
        transmitLogDO.setModifier(ACTIVITY_NAME);
        return transmitLogDO;
    }

    @Override
    public void insertLog(String employeeNum, String realName, String nickName) {
        LogDO logDO = new LogDO();
        logDO.setEmployeeNum(employeeNum);
        logDO.setNickName(nickName);
        logDO.setRealName(realName);
        logDAO.insertLog(logDO);
    }

    @Override
    public List<WinRecordDO> selectByEmployeeNum(String employeeNum) {
        return winRecordDAO.selectByEmployeeNum(employeeNum,TYPE);
    }

}
